import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams, ToastController} from 'ionic-angular';
import {Api} from "../../providers/api/api";
import {User} from "../../providers/user/user";

/**
 * Generated class for the CustomerAddPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-customer-add',
  templateUrl: 'customer-add.html',
})
export class CustomerAddPage {

  customer: { accountName: string, password: string, deadline: string, agency: string, limit: number, father: string } = {
    accountName: null,
    password: null,
    deadline: null,
    agency: null,
    limit: null,
    father: null
  };
  private title: string;
  private isAgency: boolean;

  constructor(public navCtrl: NavController,
              public api: Api,
              public user: User,
              public toastCtrl: ToastController,
              public navParams: NavParams) {
    console.log(this.navParams)
    this.customer = navParams.data;
    this.customer.agency = this.user._user.accountName;
    this.customer.father = this.user._user.accountName;
    this.isAgency = navParams.data.type == 'agency';
    this.title = navParams.data.id ? "编辑" : "添加";
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad CustomerAddPage');
  }

  saveAndUpdate() {
    if (this.customer.accountName == null || this.customer.password == null || this.customer.deadline == null) {
      return this.showToast("请填写完整信息！");
    }

    if (this.isAgency && this.customer.limit == null) {
      return this.showToast("请填写完整信息！");
    }

    let seq = this.isAgency
      ? this.api.post('agencies', this.customer).share()
      : this.api.post('customers', this.customer).share();

    if (this.navParams.data.id) {
      seq = this.isAgency
        ? this.api.put('agencies', this.customer).share()
        : this.api.put('customers', this.customer).share();
    }

    seq.subscribe((res: any) => {
      this.showToast("保存成功！");
      this.navCtrl.pop();
    }, err => {
      this.showToast(JSON.parse(err.error).title);
      console.error('ERROR', err);
    });
    return seq;
  }

  showToast(msg) {
    let toast = this.toastCtrl.create({
      message: msg,
      duration: 2000,
      position: 'top'
    });
    toast.present();
  }

}
